# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1395572054046807': {  # 新大陆支付 微信h5 3.9% 10-5000 dwc
        'API_KEY': '5Qgo8O4SWvcy2sxxssIZDUC90TOzG9X9',
        'gateway': 'http://47.75.165.243/index.php/Api/GateWay/unified_order',
        'query_gateway': 'http://47.75.165.243',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s = s[:-1] + '%s' % key
    return _gen_sign(s)


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("newlandpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 支付类型 alipay_h5：支付宝h5跳转
# wechat_qr：微信扫码
# wechat_h5：微信h5
# alipay_qr：支付宝扫码
def _get_pay_type(service):
    if service == 'alipay_h5':
        return 'alipay_h5'
    elif service == 'wechat_scan':
        return 'wechat_qr'
    elif service == 'wechat_h5':
        return 'wechat_h5'
    elif service == 'alipay_scan':
        return 'alipay_qr'
    return 'wechat_h5'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)

    parameter_dict = OrderedDict((
        ('merchant_no', str(app_id)),
        ('total_fee', str(pay_amount)),
        ('pay_type', str(_get_pay_type(service))),
        ('m_order_code', str(pay.id)),
        ('return_type', 'json'),
        ('passback_params', 'charge'),
        ('return_url', '{}/pay/api/{}/newlandpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notify_url', '{}/pay/api/{}/newlandpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("newlandpay create: %s, order_id is: %s", json.dumps(parameter_dict), str(pay.id))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info("newlandpay create rsp: %s", response.text)
    data = json.loads(response.text)
    verify_sign(data, api_key)
    return {'charge_info': data['pay_url']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("newlandpay notify data: %s", data)
    verify_sign(data, api_key)
    pay_id = data['m_order_code']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('newlandpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['order_status'])
    trade_no = str(data['sys_order_code'])
    total_fee = float(data['total_fee'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态 2：支付成功（目前只有成功的回调）
    if trade_status == '2':
        _LOGGER.info('newlandpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
